package com.cmcc.groupcontacts.firewall.activity;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;

import com.cmcc.groupcontacts.firewall.activity.strategy.WindowTitleStrategy;
import com.cmcc.groupcontacts.firewall.adapter.SelectFromCallLogAdapter;
import com.cmcc.groupcontacts.firewall.business.FilterListBusiness;
import com.cmcc.groupcontacts.firewall.dao.model.CallInfoVO;
import com.cmcc.groupcontacts.util.StringUtil;
import com.cmcc.groupcontacts.util.ValidationUtil;
import com.yinhai.activity.R;
import com.yinhai.service.ContactUserServiceImpl;

/**
 * 从通话记录中选择号码Activity
 * 
 * @author 
 * 
 */
public class SelectGroupActivityNew extends BaseListActivity {
	private boolean isBlackList = true; // 是-黑名单，否-白名单
	private FilterListBusiness filterListBiz;
	private Context context;
	@Override
	public void setTitleStrategy() {
		this.setTitle("从集团联系人添加");
		titleStrategy = new WindowTitleStrategy(this);
	}

	@Override
	public void setTitleButtons() {
		// 左边的“返回”按钮
		getLeftLayout().addView(createBackButton());
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_from_call_log_activity);
		context = this.context;
		init();
		load();
	}

	private void init() {
		isBlackList = getIntent().getBooleanExtra(FilterListActivity.IS_BLACK_LIST, true);

		findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void load() {
		// 异步加载通话记录
		new CallLogListLoadTask().execute((Void[]) null);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		CheckBox chkSelect = (CheckBox) v.findViewById(R.id.chk_select);
		if (chkSelect != null) {
			chkSelect.toggle();
			((SelectFromCallLogAdapter) l.getAdapter()).getSelectedMap().put(position, chkSelect.isChecked());
		}
	}

	/*
	 * 异步加载通话记录
	 */
	private class CallLogListLoadTask extends AsyncTask<Void, Integer, ArrayList<CallInfoVO>> {
		@Override
		protected ArrayList<CallInfoVO> doInBackground(Void... params) {
			
//			
			filterListBiz = new FilterListBusiness();
//			return filterListBiz.getCallLogList();
//			
			ContactUserServiceImpl contact = new ContactUserServiceImpl(SelectGroupActivityNew.this);
			
			return contact.findLocalContactGroup();
		}

		@Override
		protected void onPostExecute(final ArrayList<CallInfoVO> callLogs) {
			View btnOK = findViewById(R.id.btn_ok);
			if (!ValidationUtil.isNullOrEmpty(callLogs)) {
				setListAdapter(new SelectFromCallLogAdapter(SelectGroupActivityNew.this, callLogs));
				btnOK.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						SelectFromCallLogAdapter adapter = (SelectFromCallLogAdapter) getListAdapter();
						int count = adapter.getSelectedMap().size();
						ArrayList<CallInfoVO> selectedCallLogs = new ArrayList<CallInfoVO>();
						for (int i = 0; i < count; i++) {
							if (adapter.getSelectedMap().valueAt(i)) {
								selectedCallLogs.add(adapter.getItem(adapter.getSelectedMap().keyAt(i)));
							}
						}
						new ImportFilterTask(SelectGroupActivityNew.this).execute(selectedCallLogs.toArray());
					}
				});
				btnOK.setEnabled(true);
			} else {
				setListAdapter(null);
				btnOK.setEnabled(false);
			}
		}
	}

	/*
	 * 异步导入黑白名单（带进度展示）
	 */
	private class ImportFilterTask extends AsyncTask<Object, Integer, Integer> {
		private BaseActivity act;
		private ProgressDialog progressDialog;
		private int count;

		public ImportFilterTask(BaseActivity activity) {
			this.act = activity;
		}

		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialog(act);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressDialog.setTitle(R.string.processing);
			progressDialog.setMax(100);
			progressDialog.setProgress(0);
			progressDialog.setMessage(String.format(act.getString(R.string.processing_info), String.valueOf(0)));
			progressDialog.setCancelable(true);
			progressDialog.show();
		}

		@Override
		protected Integer doInBackground(Object... callLogs) {
			count = callLogs.length;
			int succeedCount = 0;
			for (int i = 0; i < count; i++) {
				CallInfoVO callLog = (CallInfoVO) callLogs[i];
				if (filterListBiz.insert(callLog, isBlackList) >= 0) {
					succeedCount++;
				}
				publishProgress(i * 100 / count);
			}
			return succeedCount;
		}

		@Override
		protected void onProgressUpdate(Integer... progresses) {
			progressDialog.setProgress(progresses[0]);
			progressDialog.setMessage(String.format(act.getString(R.string.processing_info), String.valueOf(progresses[0])));
		}

		@Override
		protected void onCancelled() {
			progressDialog.cancel();
		}

		@Override
		protected void onPostExecute(Integer succeedCount) {
			// 隐藏进度对话框
			if (SelectGroupActivityNew.this != null && !SelectGroupActivityNew.this.isFinishing()) {
				progressDialog.dismiss();
			}

			String hint = null;
			if (succeedCount == count) {
				hint = StringUtil.format("成功添加{0}个名单", count);
			} else {
				hint = StringUtil.format("添加名单成功{0}个，失败{1}个", succeedCount, count - succeedCount);
			}
			Toast.makeText(act, hint, Toast.LENGTH_LONG).show();
			act.finish();
		}
	}
}
